#!/bin/bash
set -e

rootfs=$1
if [[ ${rootfs} == "" ]]; then
    rootfs=./rootfs
fi

if [ ! -d ${rootfs} ]; then
    echo "please run script with rootfs dir:"
    echo "  ./mkrootfs.sh rootfs"
    exit -1
fi

echo "rootfs is ${rootfs}"
pushd ${rootfs}

# create init process
if [ -e "./init" ]; then
    rm ./init -rf
fi
ln -s bin/busybox init

# create /bin/bash
if [ -e "./bin/bash" ]; then
    rm ./bin/bash -rf
fi
ln -s /bin/sh bin/bash

# create base dir
mkdir -pv {bin,sbin,etc,proc,sys,usr/{bin,sbin},dev,tmp}
mkdir -p etc/init.d

# create inittab file
# this is the first boot script while system start
if [ -f "./etc/inittab" ]; then
    rm ./etc/inittab -rf
fi
cat >> etc/inittab << EOF
::sysinit:/etc/init.d/rcS
::askfirst:-/bin/sh
::restart:/sbin/init
::ctrlaltdel:/sbin/reboot
::shutdown:/bin/umount -a -r
::shutdown:/sbin/swapoff -a
EOF
chmod 755 etc/inittab

# create rcS
if [ -f "./etc/init.d/rcS" ]; then
    rm ./etc/init.d/rcS -rf
fi
cat >> etc/init.d/rcS << EOF
#!/bin/sh

mount proc
mount -o remount,rw /
mount -a

# set network
/sbin/ifconfig lo 127.0.0.1 up
/sbin/route add 127.0.0.1 lo &

ifconfig eth0 up
ip addr add 10.20.14.115/24 dev eth0
ip route add default via 10.20.14.254

clear
echo "test ......"
EOF
chmod 755 etc/init.d/rcS


# create fstab
if [ -f "./etc/fstab" ]; then
    rm ./etc/fstab -rf
fi
cat >> etc/fstab << EOF
proc     /proc proc     defaults 0 0
sysfs    /sys  sysfs    defaults 0 0
devtmpfs /dev  devtmpfs defaults 0 0
EOF

# tar x86 arch file system
find . | cpio -o --format=newc | gzip > ../rootfs.img.gz

popd

qemu-img create rootfs.ext4 1G
mkfs.ext4 -F rootfs.ext4 -d ${rootfs}

